
package com.zhu.salesmanagement.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

/**
 * 数据库Provider
 */
public class SalesProvider extends ContentProvider {

    private static final String TAG = "SalesProvider";

    private DatabaseHelper mDatabaseHelper;
    private static final String DATABASE_NAME = "sales.db"; //数据库名字
    private static final int DATABASE_VERSION = 4; //版本
    public static final String AUTHORITY = "com.dms2.salesmanagement.Provider"; //AUTHORITY
    public static final String PARAMETER_NOTIFY = "notify";

    public static final String TABLE_STOCKCHECKINFO = "storecheckinfo"; //门店CRC考核表
    public static final String TABLE_MYADDSTORES = "newaddstores"; //新增门店表
    public static final String TABLE_REMINDS = "reminds"; //提醒消息表
    public static final String TABLE_VISITEDSTORES = "visitedstores"; //拜访清单表
    public static final String TABLE_CUSTOMERS = "customers"; //客户表
    public static final String TABLE_PRODUCTCATEGORYS = "productcategorys"; //产品大类表
    public static final String TABLE_PRODUCTS = "products"; //产品表
    public static final String TABLE_PRODUCTSHELFS = "productshelfs"; //货架信息表
    public static final String TABLE_STOREPHOTOS = "storephotos"; //门店照片表
    public static final String TABLE_ISTANDARD = "integrationStandard"; //大区考核表
    public static final String TABLE_PUSHERINFO = "pusherinfo"; //导购表

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        int count = db.delete(args.table, args.where, args.args);
        if (count > 0)
            sendNotify(uri);

        return count;
    }

    @Override
    public String getType(Uri arg0) {
        SqlArguments args = new SqlArguments(arg0, null, null);
        if (TextUtils.isEmpty(args.where)) {
            return "vnd.android.cursor.dir/" + args.table;
        } else {
            return "vnd.android.cursor.item/" + args.table;
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {

        SqlArguments args = new SqlArguments(uri);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        final long rowId = db.insert(args.table, null, initialValues);
        if (rowId <= 0)
            return null;

        uri = ContentUris.withAppendedId(uri, rowId);
        sendNotify(uri);

        return uri;
    }

    private void sendNotify(Uri uri) {
        String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
        if (notify == null || "true".equals(notify)) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
    }

    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        mDatabaseHelper = new DatabaseHelper(getContext());
        return (mDatabaseHelper == null) ? false : true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {

        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(args.table);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
        result.setNotificationUri(getContext().getContentResolver(), uri);

        return result;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        int count = db.update(args.table, values, args.where, args.args);
        if (count > 0)
            sendNotify(uri);

        return count;
    }

    public static class DatabaseHelper extends SQLiteOpenHelper {

        private Context mContext = null;

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL("Create table "
                    + TABLE_STOCKCHECKINFO + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sDatingTaskActualID TEXT," +
                    "sCustomerID TEXT," +
                    "sProductCategoryID TEXT," +
                    "iShelfCount INTEGER NOT NULL DEFAULT -100," +
                    "iShelfLayer INTEGER NOT NULL DEFAULT -100," +
                    "iShelfArea INTEGER NOT NULL DEFAULT -100," +
                    "sShelfType INTEGER NOT NULL DEFAULT -100," +
                    "sCrcs TEXT," +
                    "sCompetitionMSG TEXT," +
                    "sImportantMSG TEXT," +
                    "iDatatype INTEGER" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_PUSHERINFO + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sCustomerID TEXT," +
                    "iEmployeeSId TEXT," +
                    "sEmployeeName TEXT," +
                    "sMobile TEXT," +
                    "sEmployeeCategory TEXT," +
                    "sAccreditCategoryDescription TEXT," +
                    "dRegisterDate INTEGER" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_MYADDSTORES + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sStoreName TEXT," +
                    "sStoreType TEXT," +
                    "sStoreAddress TEXT," +
                    "sStoreContact TEXT," +
                    "sStoreTel TEXT," +
                    "sCustomerId TEXT," +
                    "photo BLOB," +
                    "sLat TEXT," +
                    "sLng TEXT," +
                    "sSp1 TEXT," +
                    "sSp2 TEXT," +
                    "sSp3 TEXT," +
                    "sSp4 TEXT," +
                    "sSp5 TEXT," +
                    "sSp6 TEXT," +
                    "iSp7 INTEGER," +
                    "iSp8 INTEGER," +
                    "iSp9 INTEGER," +
                    "iSp10 INTEGER," +
                    "iSp11 INTEGER," +
                    "iSp12 INTEGER," +
                    "iSp13 INTEGER," +
                    "sSp14 TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_REMINDS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sEmployeeID TEXT," +
                    "iRemindMSGID TEXT," +
                    "sRemindMSGText TEXT," +
                    "dRemindTime INTEGER," +
                    "iCycleCategory INTEGER," +
                    "sCustomerID TEXT," +
                    "sEventid TEXT," +
                    "dRemindDeadline INTEGER" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_VISITEDSTORES + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sEmployeeID TEXT," +
                    "sDatingTaskActualID TEXT," +
                    "iDatingTaskID TEXT," +
                    "dPlanningDate TEXT," +
                    "sAssignedEmployeeID TEXT," +
                    "iItemNo INTEGER NOT NULL DEFAULT 100," +
                    "sCustomerID TEXT," +
                    "sCheckinlat TEXT," +
                    "sCheckinlng TEXT," +
                    "sCheckintime TEXT," +
                    "sCheckresult TEXT," +
                    "sCheckinfo TEXT," +
                    "iVisitCategory INTEGER NOT NULL DEFAULT 0," +
                    "iPutStatus INTEGER NOT NULL DEFAULT 0," +
                    "iPutSuccess INTEGER NOT NULL DEFAULT 0" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_CUSTOMERS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sCustomerID TEXT," +
                    "sCustomerName TEXT," +
                    "sAreaID TEXT," +
                    "iVisitCategory TEXT," +
                    "sCustomerAddress TEXT," +
                    "decLatitude TEXT," +
                    "decLongitude TEXT," +
                    "sCRCNearTime TEXT," +
                    "sSCNearTime TEXT," +
                    "sDealtEmployeeID TEXT," +
                    "sDealtSalesPerson TEXT," +
                    "sStoreLevel TEXT," +
                    "sStoreCategory TEXT," +
                    "sImportantMSG TEXT," +
                    "dAddTime INTEGER," +
                    "iStorePropertyInquire INTEGER NOT NULL DEFAULT 0" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_PRODUCTCATEGORYS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sProductCategoryID TEXT," +
                    "sProductCategory TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_PRODUCTS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sProductCategoryID TEXT," +
                    "sProductID TEXT," +
                    "iSort INTEGER," +
                    "sProductName TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_PRODUCTSHELFS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sCustomerID TEXT," +
                    "sProductCategoryID TEXT," +
                    "iShelfCount TEXT," +
                    "iShelfLayer TEXT," +
                    "iShelfArea TEXT," +
                    "sShelfType TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_STOREPHOTOS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sCustomerId TEXT," +
                    "sPhotoSource TEXT," +
                    "sDatingTaskActualID TEXT," +
                    "decPhotoLongitude TEXT," +
                    "decPhotoLatitude TEXT," +
                    "dShootDate TEXT," +
                    "data BLOB," +
                    "iSort INTEGER" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_ISTANDARD + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "iItemNo TEXT," +
                    "sItemDescription TEXT," +
                    "sAreaID TEXT," +
                    "sAreaName TEXT" +
                    ");");
            
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            if (DATABASE_VERSION != oldVersion) {
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_MYADDSTORES);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_VISITEDSTORES);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_CUSTOMERS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTCATEGORYS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTSHELFS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_ISTANDARD);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_STOREPHOTOS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_PUSHERINFO);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_STOCKCHECKINFO);
                onCreate(db);
            }
        }
    }

    static class SqlArguments {
        public final String table;
        public final String where;
        public final String[] args;

        SqlArguments(Uri url, String where, String[] args) {
            if (url.getPathSegments().size() == 1) {
                this.table = url.getPathSegments().get(0);
                this.where = where;
                this.args = args;
            } else if (url.getPathSegments().size() != 2) {
                throw new IllegalArgumentException("Invalid URI: " + url);
            } else if (!TextUtils.isEmpty(where)) {
                throw new UnsupportedOperationException("WHERE clause not supported: " + url);
            } else {
                this.table = url.getPathSegments().get(0);
                this.where = "_id=" + ContentUris.parseId(url);
                this.args = null;
            }
        }

        SqlArguments(Uri url) {
            if (url.getPathSegments().size() == 1) {
                table = url.getPathSegments().get(0);
                where = null;
                args = null;
            } else {
                throw new IllegalArgumentException("Invalid URI: " + url);
            }
        }
    }
}
